const program = require('commander')
  , Dashboard = require('./dashboard')
  , fs = require('fs')
  , os = require('os')

const cfgFile = os.homedir().concat('/.wlog.json')

if(!fs.existsSync(cfgFile)) generateConfigFile()

program
  .version('1.0.0')
  .option('add, --cfg [type]', 'add new log config')
  .parse(process.argv)

if (process.argv.length > 2) {
  switch(process.argv.length) {
    case 3: {
      processSSH()
      break
    }
    case 4: {
      processAdd()
      break
    }
  }

} else {
  new Dashboard()
}

function processSSH() {
  let cfg = JSON.parse(fs.readFileSync(cfgFile).toString())
  const argv = process.argv[2]

  const u_h = argv.split('@')
  const h_p = u_h[1].split(':')

  cfg.ssh.username = u_h[0]
  cfg.ssh.host = h_p[0]
  cfg.ssh.port = h_p[1]

  fs.writeFileSync(cfgFile, JSON.stringify(cfg))
}

function processAdd() {
  let cfg = JSON.parse(fs.readFileSync(cfgFile).toString())
  const newAdd = getAddObject(program.cfg)
  if (newAdd){
    cfg.logs.push(newAdd)
    fs.writeFileSync(cfgFile, JSON.stringify(cfg))
  }
}

function getAddObject(addCfg) {
  const a = addCfg.split(':')
  if (a.length !== 2) return null

  return {
    alias: a[0],
    path: a[1]
  }
}

function generateConfigFile() {
  const cfg = {
    ssh: {
      host: "",
      port: 22,
      username: "root",
      privateKey: os.homedir().concat('/.ssh/id_rsa')
    },
    logs: [],
  }

  fs.writeFileSync(cfgFile, JSON.stringify(cfg))
}
